//
//  UITabBar+BageValue.m
//  Personalise
//
//  Created by zhangmeng on 2017/2/21.
//  Copyright © 2017年 马玉景. All rights reserved.
//

#import "UITabBar+BageValue.h"
#define TabbarItemNums 4.0    //tabbar的数量 如果是5个设置为5.0
@implementation UITabBar (BageValue)

//显示小红点
- (void)showBadgeOnItemIndex:(int)index andCount:(int)count{
    //移除之前的小红点
    [self removeBadgeOnItemIndex:index];
    
    //新建小红点
    UIView *badgeView = [[UIView alloc]init];
    badgeView.tag = 888 + index;
    badgeView.layer.cornerRadius = 6;//圆形
    badgeView.backgroundColor = [UIColor redColor];//颜色：红色
    CGRect tabFrame = self.frame;

    
    //确定小红点的位置
    float percentX = (index + 0.3) / TabbarItemNums;
    CGFloat x = ceilf(percentX * tabFrame.size.width);
    CGFloat y = ceilf(0.11 * tabFrame.size.height);
    badgeView.frame = CGRectMake(x, y, 12, 12);//圆形大小为12
    [self addSubview:badgeView];
    
    UILabel  *countLable = [[UILabel alloc ] initWithFrame:badgeView.bounds];
    countLable.textColor = [UIColor  whiteColor];
    countLable.textAlignment = NSTextAlignmentCenter;
    countLable.font = [UIFont systemFontOfSize:9];
    countLable.adjustsFontSizeToFitWidth = YES;
    countLable.text = [NSString stringWithFormat:@"%d",count];

    if (count == 0) {
        badgeView.hidden = YES;
    }

    [badgeView  addSubview:countLable];
    
}


//隐藏小红点
- (void)hideBadgeOnItemIndex:(int)index{
    //移除小红点
    [self removeBadgeOnItemIndex:index];
}

//移除小红点
- (void)removeBadgeOnItemIndex:(int)index{
    //按照tag值进行移除
    for (UIView *subView in self.subviews) {
        if (subView.tag == 888+index) {
            [subView removeFromSuperview];
        }
    }
}


@end
